//go:generate protoc -I=. --go_out=plugins=grpc:./tms ./tms/tms.proto

package rpc

import (
    "crypto/tls"
    "fmt"
    "net"
    "time"

    "google.golang.org/grpc"
    "google.golang.org/grpc/backoff"
    "google.golang.org/grpc/credentials"
    "rpc/tms"
)

func grpc_conn(host string, port int, tls_cfg *tls.Config) *grpc.ClientConn {
    opts := []grpc.DialOption{
        grpc.WithConnectParams(grpc.ConnectParams{
            Backoff: backoff.Config{
                BaseDelay:  time.Millisecond * 100,
                Multiplier: 1.1,
                Jitter:     0.20,
                MaxDelay:   time.Second * 3,
            },
        }),
    }
    if tls_cfg == nil {
        opts = append(opts, grpc.WithInsecure())
    } else {
        opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(tls_cfg)))
    }

    conn, err := grpc.Dial(fmt.Sprintf("%s:%d", host, port), opts...)
    if err != nil {
        panic(err)
    }
    return conn
}

func NewTMSClient(host string, port int, tls_cfg *tls.Config) tms.TMSClient {
    return tms.NewTMSClient(grpc_conn(host, port, tls_cfg))
}

func NewTMSServer(host string, port int, tls_cfg *tls.Config, srv tms.TMSServer) error {
    var rpc_srv *grpc.Server
    if tls_cfg != nil {
        rpc_srv = grpc.NewServer(grpc.Creds(credentials.NewTLS(tls_cfg)))
    } else {
        rpc_srv = grpc.NewServer()
    }
    tms.RegisterTMSServer(rpc_srv, srv)

    ln, err := net.Listen("tcp", fmt.Sprintf("%s:%d", host, port))
    if err != nil {
        return err
    }
    go func() {
        _ = rpc_srv.Serve(ln)
    }()
    return nil
}
